package org.meetunexpectedly.util;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;


/**
 * @Description: 数据加密和解密工具
 * @Author: pupil
 * @Date: 2024/08/10 下午 6:06
 */
@Service(value = "encryptionUtil")
public class EncryptionUtil {

    // 密钥  DES模式：8位字节长度      AES模式：16位字节长度
    // 默认密钥：PupilQWQ
    @Value("${spring.encryption.key:PupilQWQ}")
    private String key;

    // 加密方式
    // 默认模式：DES
    @Value("${spring.encryption.transformation:DES}")
    private String transformation;

    /**
     * 加密
     *
     * @param text 明文
     * @return
     */
    public String encrypt(String text){
       try {
           Cipher cipher = Cipher.getInstance(transformation);
           //    key          与给定的密钥内容相关联的密钥算法的名称
           SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), transformation);
           //Cipher 的加密模式：ENCRYPT_MODE
           cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
           byte[] bytes = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
           return Base64.encode(bytes);
       }catch (Exception e){
           e.printStackTrace();
       }
       return null;
    }

    public String decrypt(String text){
        try {
            Cipher cipher = Cipher.getInstance(transformation);
            //    key          与给定的密钥内容相关联的密钥算法的名称
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), transformation);
            //Cipher 的解密模式：DECRYPT_MODE
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] bytes = cipher.doFinal(Base64.decode(text));
            return new String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
